/*
 * Created on Oct 3, 2004
 */
package org.vectrics.provider;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
import org.vectrics.SystemException;
import org.vectrics.hibernate.ApplicationContext;
import org.vectrics.hibernate.ThreadProperties;


/**
 * @author mmoore
 */
public class BeanLocator {
	private static Logger log = Logger.getLogger(BeanLocator.class);
	
    public static Object findBean(String code) {
        Object service = null;
    	ApplicationContext appInfo = ThreadProperties.getApplicationContext();
    	if (appInfo == null) {
    		throw new SystemException("ThreadProperties does not have applicationContext set");
    	}
        try {
        	
        	if (log.isDebugEnabled()) {
	        	log.debug("findBean()" +
	        			"\r\n - bean code = " + code +
	        			"\r\n - application name = " + appInfo.getName()
	        			);
        	}
        	
        	BeanFactory beanFactory = appInfo.getBeanFactory();
        	if (beanFactory == null)
        		throw new SystemException("Bean factory was not attached to thread");
        	
        	service = beanFactory.getBean(code);        
        	} catch (Exception ex) {
        	//service = null;
        	throw new SystemException("Could not find bean" +
        			"\r\n - Code               = " + code +
        			"\r\n - ApplicationContext = " + appInfo
        			);
        }
        return(service);
    }
   
}
